package com.hxzy.driver.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowItem;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author wy
 * @Description 自定义流量控制规则
 * @Date 2023/12/13 11:51
 * @Version 1.0
 */
@Configuration
public class SentinelRuleConfig {

    /**
     * 流量控制规则
     */
    private static void initFlowRules(){
        //添加N个流量控制规则
//        List<FlowRule> rules = new ArrayList<>();
//
//        //第一个
//        FlowRule rule = new FlowRule();
//        rule.setResource("HelloWorld");
//        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//        // Set limit QPS to 20.
//        rule.setCount(20);
//        rules.add(rule);
//        FlowRuleManager.loadRules(rules);

    }

    @PostConstruct
    public void init(){

        initParamFlowRule();
    }

    /**
     * 热点规则
     */
    private   void initParamFlowRule(){
        // 单机阈值 count=20
        ParamFlowRule rule = new ParamFlowRule("driver_hot") .setParamIdx(0).setCount(500);

        List<ParamFlowItem>  items=new ArrayList<>();

        // 规则1，针对 int 类型的参数 PARAM_B，单独设置限流 QPS 阈值为 10， 而不是全局的阈值 20
        ParamFlowItem item = new ParamFlowItem().setObject(String.valueOf(1000))
                .setClassType(Long.class.getName())
                .setCount(1);
        items.add(item);


        //规则2
        // 针对 int 类型的参数 PARAM_B，单独设置限流 QPS 阈值为 10， 而不是全局的阈值 20
        ParamFlowItem item2 = new ParamFlowItem().setObject(String.valueOf(2000))
                .setClassType(Long.class.getName())
                .setCount(3);
        items.add(item2);

        rule.setParamFlowItemList(items);

        //添加热点规则中去
        ParamFlowRuleManager.loadRules(Collections.singletonList(rule));

    }

}
